// components/color-picker/color-picker.js
const util = require('../../utils/utils.js')
let colorPickerCtx = {}; // 外环的canvas环境
let controlCtx = {}; // 内圈的canvas环境
let canvas = null // 内圈的canvas

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    raduis: 350, // 图形的大小，这里最大为750rpx铺满屏幕
    ringWidthOrHeight: 350, // 圆环的直径
    pickColor: null, // 选择的颜色值
    hsl: { // pickColor的hsl值，防止在滑动slider的时候小圆点会有移动
      h: 0,
      s: 0,
      l: 0
    },
    sliderColor: null, // slider渐变颜色值
    sliderValue: 0 // slider的value值
  },

  lifetimes: {
    attached () {
      let initColor = '255,0,0'
      let hsl = util.rgbTohsl(initColor);
      console.log(hsl)
      this.setData({
        pickColor: initColor,
        sliderColor: initColor,
        hsl: {
          h: hsl[0],
          s: hsl[1],
          l: hsl[2]
        },
        sliderValue: hsl[2] * 100
      })

      // 在组件实例进入页面节点树时执行
      this.drawProgressbg();
      this.drawControlPoint();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    drawProgressbg: function(){
      const query = wx.createSelectorQuery().in(this)
      query.select('.progress_bg')
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node
          colorPickerCtx = canvas.getContext('2d')
          // 不加这段圆环会绘制错误
          // const dpr = wx.getSystemInfoSync().pixelRatio
          const dpr = 2 // 有点问题设置一下
          // 根据分辨率设置画布宽高
          canvas.width = res[0].width * dpr
          canvas.height = res[0].height * dpr
          this.setData({
            ringWidthOrHeight: canvas.width
          })
          colorPickerCtx.scale(dpr, dpr)
          util.drawRing(colorPickerCtx, canvas.width/2)
        })
    },
    drawControlPoint: function () {
      const query = wx.createSelectorQuery().in(this)
      query.select('.control_point')
        .fields({ node: true, size: true })
        .exec(res => {
          canvas = res[0].node
          controlCtx = canvas.getContext('2d')
          // 不加这段圆环会绘制错误
          // const dpr = wx.getSystemInfoSync().pixelRatio 
          const dpr = 2
          // 根据分辨率设置画布宽高
          canvas.width = res[0].width * dpr
          canvas.height = res[0].height * dpr
          util.drawSlider(controlCtx, canvas.width, canvas.height, 1.0, 0.5)
      })
    },
    handlePointMove: function (e) {
      if (e.touches) {
        const mouseX = e.changedTouches[0].pageX
        const mouseY = e.changedTouches[0].pageY
        const color = this.updateCanvasByMousePos(mouseX, mouseY);
        let hsl = util.rgbTohsl(color);

        canvas.requestAnimationFrame(() => {
          util.drawSlider(controlCtx, this.data.ringWidthOrHeight, this.data.ringWidthOrHeight, hsl[0], this.data.sliderValue / 100)
        });
      }
    },

    handleTouchEnd: function () {
      const {pickColor} = this.data
      console.log('鼠标停止了，准备发送广播包, color:', pickColor)
      this.triggerEvent('changeLightColor', {pickColor})
    },
    
    // 通过鼠标所在点更新Canvas画图信息
    updateCanvasByMousePos: function (x, y){
      let currentAngle = util.getRotateAngle(x, y, this.data.ringWidthOrHeight);
      return this.updateCanvasByAngle(currentAngle);
    },
    //通过角度更新Canvas画图信息位置
    updateCanvasByAngle: function (angle) {
      // const {curColor, circleWidth} = this.data.baseCircle
      // const {ringWidthOrHeight} = this.data
      // var newX = ringWidthOrHeight + - Math.cos(angle*Math.PI/180) * (ringWidthOrHeight/2-circleWidth);
      // var newY = ringWidthOrHeight - Math.sin(angle* Math.PI/180) * (ringWidthOrHeight/2-circleWidth);
    
      // const color = 'rgb('+this.getAngleColor(((angle+180)%360)/180 * Math.PI)+')'
      // 这里先改成数字
      const color = util.getAngleColor(((angle+180)%360)/180 * Math.PI)
      console.log(color, 'color')
      let hsl = util.rgbTohsl(color);
      let colorWithSlider = util.hslToRgb(hsl[0], hsl[1], this.data.sliderValue/100)
      // console.log("new : ", newX, newY,"\ncur color is :" + color);
      this.setData({
        pickColor: colorWithSlider,
        sliderColor: color,
        'hsl.h': hsl[0],
        // 'hsl.s': hsl[2]
      })
      return color
    },
    changeColor: function (e) { // 更新亮度hsl中l的值
      let value = e.detail.value
      // let { pickColor} = this.data;
      // let [h, s, l] = util.rgbTohsl(pickColor)
      const {h, s} = this.data.hsl
      const lightUnit = value / 100
      const newColor = util.hslToRgb(h, s, lightUnit)
      controlCtx.fillStyle = `rgb(${newColor[0]},${newColor[1]},${newColor[2]})`
      controlCtx.fill()
      this.triggerEvent('changeLightColor', {pickColor: newColor})
      this.setData({ // 这里不更新hsl的值，放置小数误差导致小圆点有滑动
        sliderValue: value,
        pickColor: `${newColor[0]},${newColor[1]},${newColor[2]}`
        // hsl: {
        //   h,
        //   s,
        //   l
        // }
      })
      canvas.requestAnimationFrame(() => {
        util.drawSlider(controlCtx, this.data.ringWidthOrHeight, this.data.ringWidthOrHeight, h, lightUnit)
      });
    }
  }
})
